package com.qianyu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianyu.api.ApiCommon;
import com.qianyu.entity.base.BaseIdDto;
import com.qianyu.entity.bean.QqAccount;
import com.qianyu.entity.dto.QqAccountDto;
import com.qianyu.entity.vo.QqAccountVo;
import com.qianyu.mapper.QqAccountMapper;
import com.qianyu.service.QqAccountService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class QqAccountServiceImpl extends ServiceImpl<QqAccountMapper, QqAccount> implements QqAccountService {

    private final ApiCommon apiCommon;

    /**
     * 新增qq账号
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveQqAccount(QqAccountDto.QqAccountSaveDto dto) {
        String result = apiCommon.applyQq(dto.getNum());
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") != 0) {
            return false;
        }
        List<QqAccount> accounts = new ArrayList<>();
        JSONArray array = jsonObject.getJSONArray("data");
        for (Object o : array) {
            JSONObject object = (JSONObject) o;
            QqAccount account = new QqAccount() {{
                setQq(object.getString("qq"));
                setRole(dto.getRole());
                setProvinceCode(object.getString("province"));
                setTag(dto.getRemark());
            }};
            accounts.add(account);
        }

        return saveBatch(accounts);
    }

    /**
     * 分页筛选账号
     *
     * @param dto
     * @return
     */
    @Override
    public Page<QqAccount> pageList(QqAccountDto.QqAccountPageDto dto) {
        return (Page<QqAccount>) page(new Page<>(dto.getPageNum(), dto.getPageSize()),
                Wrappers.<QqAccount>lambdaQuery()
                        .eq(ObjectUtil.isNotNull(dto.getStatus()), QqAccount::getStatus, dto.getStatus())
                        .eq(ObjectUtil.isNotNull(dto.getRole()), QqAccount::getRole, dto.getRole())
                        .like(!StringUtils.isEmpty(dto.getQq()), QqAccount::getQq, dto.getQq()));
    }

    /**
     * 查询账号详情
     *
     * @param dto
     * @return
     */
    @Override
    public QqAccount getInfo(BaseIdDto dto) {
        return getById(dto.getId());
    }

    /**
     * 获取未实名账号
     */
    @Override
    public QqAccountVo.QqAccountSimpleVo getNoAuthAccount() {
        LambdaQueryWrapper<QqAccount> wrapper = Wrappers.lambdaQuery();
        wrapper.select(QqAccount::getQq, QqAccount::getProvinceCode).eq(QqAccount::getAuthed, 0).eq(QqAccount::getStatus, 0).last(" limit 1");
        return BeanUtil.copyProperties(getOne(wrapper), QqAccountVo.QqAccountSimpleVo.class);
    }

    /**
     * 认证回调方法
     *
     * @param dto
     * @return
     */
    @Override
    public boolean authAccount(QqAccountDto.QqAccountAuthDto dto) {

        LambdaUpdateWrapper<QqAccount> wrapper = Wrappers.lambdaUpdate();
        wrapper.set(QqAccount::getStatus, dto.getStatus());
        if (dto.getStatus() == 1) {
            wrapper.set(QqAccount::getAuthed, 1)
                    .set(QqAccount::getAuthTime, DateUtil.date())
                    .set(QqAccount::getAuthIdNo, dto.getIdNo())
                    .set(QqAccount::getAuthPhone, dto.getPhone())
                    .set(QqAccount::getAuthPwd, dto.getPwd())
                    .set(QqAccount::getRemark, dto.getRemark());
        }
        wrapper.eq(QqAccount::getQq, dto.getQq());

        return update(wrapper);
    }

    /**
     * 随机获取建号qq
     */
    @Override
    public QqAccount getRandomAccount() {
        return getOne(Wrappers.<QqAccount>lambdaQuery()
                .eq(QqAccount::getRole, 0)
//                .eq(QqAccount::getStatus, 1)
                .eq(QqAccount::getSeatStatus, 0).last(" limit 1"));
    }

    /**
     * 根据条件获取账号
     *
     * @param role
     * @param num
     */
    @Override
    public List<QqAccount> getAccounts(Integer role, Integer num) {

        return baseMapper.getAccounts(role, num);
    }

    /**
     * 冻结qq
     *
     * @param qq
     * @param remark
     */
    @Override
    public boolean freezeAccount(String qq, String remark) {
        return update(Wrappers.<QqAccount>lambdaUpdate().set(QqAccount::getStatus, -1)
                .set(QqAccount::getRemark, remark).eq(QqAccount::getQq, qq));
    }
}
